import classNames, {Argument, Mapping, Value} from "classnames"

export const CUSTOM_SCHOOL_LOGO_IDS = ['S-XHWLXX', 'S-zjzx']

const valueArray = ["string", "number", "boolean"]

export function isValue(value: any): Value | null {
  return valueArray.includes(typeof value) ? value : null
}

export function isMapping(value: any): Mapping | null {
  return Object.prototype.toString.call(value) === '[object Object]' ? value : null
}

export function isArguments(value: any): Argument[] | null {
  return Array.isArray(value) ? value : null
}

export function paddingPrefix(prefix: string, args: Argument[]): Argument[] {
  if (args.length <= 0) {
    return []
  }

  return args.map(item => {
    if (isValue(item)) {
      return typeof item === "string" ? `${prefix}-${item}` : item
    }
    if (isMapping(item)) {
      const newItem: Mapping = {}
      Object.keys(item as Mapping).forEach(key => {
        if (Object.prototype.hasOwnProperty.call(item, key)) {
          newItem[`${prefix}-${key}`] = (item as Mapping)[key]
        }
      })
      return newItem
    }
    if(isArguments(item)){
      return paddingPrefix(prefix, item as Argument[])
    }
    return null
  })
}

export const createClassFun = (prefix: string) => {
  const classNamesPrefix = (...args: Argument[]) => {
    return classNames(paddingPrefix(prefix, args))
  }

  const rootClass = (propClassName: string, ...args: Argument[]) => {
    return classNames(
      `${prefix}-root`,
      classNamesPrefix(args),
      {
        [`${propClassName}`]: !!propClassName
      }
    )
  }


  return{
    classNames: classNamesPrefix,
    rootClass
  }
}

//解析URL
export function parseUrl(str:any):any{//JS正则表达式解析URL(协议/域名/端口/路径/参数/锚点)
  const options = {
    key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
    q: {
      name: "queryKey",
      parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
  }

  if (!str) {
    return '';
  }

  let m = options.parser.loose.exec(str) as any
  let uri = {}
  let i = 14

  while (i--) uri[options.key[i]] = m[i] || "";

  uri[options.q.name] = {};
  uri[options.key[12]].replace(options.q.parser, function (_:string, $1:string, $2:string) {
    if ($1) uri[options.q.name][$1] = $2;
  });

  return uri;
}
